<template>
	<view class="auth-index">
		<view class="logo">
			<u-image class="logo-img" width="250rpx" height="250rpx" :src="`${staticUrl}/login_img2.png`"></u-image>
		</view>

		<view class="fotter">


			<view class="btns">

				<!-- #ifdef APP-PLUS -->
				<!-- <u-button 
					type="default" 
					hover-class="none"
					:hair-line="false"
					:custom-style="oneLoginBtnStyle"
					@click="goUserLogin(1)"
					:loading="oneLoginBtn.load"
				>APP一键登录</u-button> -->
				<!-- #endif -->

				<!-- #ifndef APP-PLUS -->
				<u-button type="default" hover-class="none" :hair-line="false" :custom-style="oneLoginBtnStyle"
					open-type="getPhoneNumber" @getphonenumber="decryptWxPhoneNumber" :loading="oneLoginBtn.load">
					<!-- <u-icon name="weixin-fill" color="#ffffff" size="28" :custom-style="{'margin-right': '10rpx'}"></u-icon> -->
					手机快捷登录
				</u-button>
				<!-- #endif -->

				<u-button type="default" hover-class="none" :hair-line="false" :custom-style="accPhoneLoginBtnStyle"
					@click="goUserLogin(2)">
					<u-icon name="/static/icons/phone-fff.png" color="#ffffff" size="28"
						:custom-style="{'margin-right': '4rpx'}"></u-icon>
					账号登录
				</u-button>

				<u-button type="default" hover-class="none" :hair-line="false" :custom-style="noLoginBtnStyle"
					@click="goUserLogin(3)">
					<u-icon name="close" color="#00c3ce" size="28" :custom-style="{'margin-right': '10rpx'}"></u-icon>
					暂不登录
				</u-button>
			</view>

			<view class="login-tip">说明：只为客车帮平台所在车队驾驶员提供登录，如没有账号请联系所属车队管理员注册！</view>
		</view>
		<u-picker @cancel='login_cancel' @confirm='login_confirm' v-model="login_show" mode="selector"
			:default-selector="[0]" :range="selector" range-key="companyName"></u-picker>
		<u-modal :show-confirm-button='false'  v-model="show_chushihua" :content="'账号第一次登录正在初始化,请耐心等待几秒...'"></u-modal>
		<u-modal  @confirm='longin_confirm' v-model="longin_model" :content="longin_text"></u-modal>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				longin_model:false,
				longin_text: '',
				show_chushihua:false,
				decres: '',
				selector: [],
				login_show: false,
				// 登录授权code
				loginCode: '',
				// 网络静态资源地址
				staticUrl: this.C.staticNetUrl,
				// 微信登录按钮
				oneLoginBtn: {
					load: false,
					text: '微信一键登录'
				},
				// 微信登录按钮样式
				oneLoginBtnStyle: {
					'margin': '0 0rpx',
					'padding': '0 20rpx',
					'background-color': '#00c3ce',
					'border-color': '#00c3ce',
					'color': '#ffffff',
					'font-weight': '600'
				},
				// 手机/账号登录按钮样式
				accPhoneLoginBtnStyle: {
					'margin': '0 0rpx',
					'padding': '0 20rpx',
					'background-color': '#19be6b',
					'border-color': '#19be6b',
					'color': '#ffffff',
					'font-weight': '600'
				},
				// 暂不登录按钮样式
				noLoginBtnStyle: {
					'margin': '0 0rpx',
					'padding': '0 20rpx',
					'border-color': '#00c3ce',
					'color': '#00c3ce',
					'font-weight': '600'
				}
			}
		},
		onShow() {
			const that = this,
				U = that.U,
				C = that.C;

			// 已登录，跳转到tabbar主页
			let luuid = uni.getStorageSync(C.uuid);
			if (luuid) uni.switchTab({
				url: '/pages/tabbar/order-list/order-list'
			});

			//#ifdef MP-WEIXIN
			uni.checkSession({
				success(res) {
					console.log('成功：检查session是否过期', res);

					// 调用login接口
					uni.login({
						provider: 'weixin',
						success: function(lres) {
							console.log('登录结果', lres);
							if (!lres.code) {
								that.U.qalert('code为空');
							} else {
								that.loginCode = lres.code;
							}
						},
						fail: function(err) {
							console.log('失败：登录结果', err);
						}
					});
				},
				fail(err) {
					console.log('失败：检查session是否过期', err);
					// U.qalert('第一次登录错误，请联系技术人员。');

					// 调用login接口
					uni.login({
						provider: 'weixin',
						success: function(lres) {
							console.log('第一次登录授权结果', lres);
							if (!lres.code) {
								that.U.qalert('code为空');
							} else {
								that.loginCode = lres.code;
							}
						},
						fail: function(err) {
							console.log('失败：登录结果', err);
						}
					});
				}
			});
			//#endif
		},
		onLoad(e) {
			console.log('地址传入的参数', e);
			if (e.tno) uni.setStorageSync('lteamNo', e.tno);
		},
		methods: {
			/**
			 * 用户登录
			 * @param {Number} type 1-微信一键登录 2-手机/账号密码登录
			 */
			goUserLogin(type) {
				const that = this,
					U = that.U;
				//#ifndef APP-PLUS || H5
				uni.getSetting({
					withSubscriptions: true,
					success(res) {
						let set = res.authSetting;
						console.log('是否授权位置', res, '1111111');
						console.log('是否授权位置', res.subscriptionsSetting, '2222222');
						if (!set['scope.userLocationBackground']) {
							// 地址未授权
							U.qmodal({
								title: '温馨提示',
								text: '请授权定位服务，以便更好的体验！',
								success: res => {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												console.log('打开设置成功', res.authSetting)
											}
										})
									}
								}
							});
						} else {
							if (type == 1) {
								// 调用小程序一键登录
								// that.oneLogin();
							} else if (type == 2) {
									
								// 导航-手机/账号密码登录页面
								that.goLogin();
							}
						}
					}
				});
				//#endif

				//#ifdef APP-PLUS
				if (type == 1) {
					// 调用APP一键登录
					that.appOneLogin();
				} else if (type == 2) {
					// 导航-手机/账号密码登录页面
					that.goLogin();
				}
				//#endif

				if (type == 3) { // 暂不登录
					uni.navigateTo({
						url: '../app-explain/app-explain'
					});
				}



			},
			// 微信一键登录
			oneLogin() {
				console.log('微信一键登录');
			},
			login_cancel() {
				let that = this,
					U = that.U;
				U.qerror('已取消登录');
				that.oneLoginBtn.load = false;
			},
			login_confirm(e) {
				let that = this,
					U = that.U;
				let ps2 = {
					// openId: decres.openId,
					// lphone: decres.phone, 		// 正式

					// openId: 'oDaPO5ewTSOUo12_gRDj8vAG-F9E',
					// lphone: '17828028717', 	// 测试

					// lphone: '18349307058',

					// loginType: login_identity_data.value,
					openId: that.decres.data.openId,
					phone: that.decres.data.phone,
					miniType: '1'
				}
				ps2.companyNum = that.selector[e].companyNum

				that.$u.api.wxMpLogin(ps2).then(loginres => {
					if (loginres.code != 1) {
						if (loginres.code == -1) {
							
							that.show_chushihua = true
							let tiem = null
							tiem = setTimeout(()=> {
								that.show_chushihua = false
								uni.showToast({
									title: '初始化成功请重新登录',
									duration: 1000,
									icon:'none'
								});
								clearTimeout(tiem)
							}, 10000);
							

						} else {
							U.qalert(loginres.msg);
						}

					} else {
						// console.log(loginres.data.luser.checkCarTips,loginres.data.luser.buySafeTips,loginres.data.luser.isHaveCompany)
						// 保存登录用户uuid
						// console.log(loginres, 'loginres')
						uni.setStorageSync(that.C.uuid, loginres.data
							.token);
						uni.setStorageSync('token', loginres.data.token);
						uni.setStorageSync('staffState', loginres.data.luser.staffState);
						uni.setStorageSync('lrole', loginres.data.luser.lrole);
						// 获取登录用户信息
						that.$u.api.getLuserInfo({}).then(res => {
							if (res.code == 1) {
								// 保存登录用户信息
								uni.setStorageSync(that.C.luser, res.data);
						
								
							}
						});
						// 获取登录用户信息
						that.$u.api.getLUserInfo({}).then(res => {
							if (res.code == 1) {
								// 保存登录用户信息
								uni.setStorageSync('isTrustee', res.data.company.isTrustee);
						
								
							}
						});
						if(loginres.data.luser.checkCarTips || loginres.data.luser.buySafeTips){
							if(loginres.data.luser.checkCarTips){
								that.longin_text = loginres.data.luser.checkCarTips
							}
							if(loginres.data.luser.buySafeTips){
								that.longin_text +=loginres.data.luser.buySafeTips
							}
							uni.setStorageSync('longin_text', that.longin_text);
							that.longin_model = true
						}else{
							
							// uni.setStorageSync(that.C.luser, loginres.data
							// 	.luser);
							uni.switchTab({
								url: '/pages/tabbar/order-list/order-list'
							});
							
						}
						
						
					}
				});


			},
			longin_confirm(){
				this.longin_model = false
				uni.switchTab({
					url: '/pages/tabbar/order-list/order-list'
				});
			},
			// 微信解密手机号
			decryptWxPhoneNumber(e) {
				const that = this,
					U = that.U;
				console.log('授权结果', e);
				if (!e.detail.encryptedData) {
					U.qinfo('抱歉，您拒绝了授权，部分功能将不能体验！');
				} else {
						uni.setStorageSync('loginId', '1');
					that.oneLoginBtn.load = true;
					uni.getSetting({
						success(setres) {
							let set = setres.authSetting;
							console.log('是否授权位置', set);

							if (!set['scope.userLocationBackground']) {
								// 地址未授权
								U.qmodal({
									title: '温馨提示',
									text: '授权定位服务，以便更好的体验！请选择【使用小程序期间和离开小程序后】',
									success(mdres) {
										if (mdres.confirm) {
											uni.openSetting({
												success(openres) {
													console.log('打开设置成功', openres.authSetting)
												}
											})
										}
									}
								});
							} else {
								let ps = {
									code: that.loginCode,
									encryptedData: e.detail.encryptedData,
									iv: e.detail.iv,
									miniType: '1',
								};
								that.oneLoginBtn.load = true, U.qloading('登录中...');
								that.$u.api.wxDecodePhone(ps).then(decres => {
									that.oneLoginBtn.load = false;
									that.decres = decres
									console.log(that.decres,'手机openid')
									if (decres.code == 1) {
										console.log('解密手机号', decres);
										that.$u.api.getCompanyByPhone({
											loginPhone: decres.data.phone,
										}).then((res) => {
											if (res.code == 1) {
												if (res.data.length > 0) {
													that.login_show = true
													that.selector = res.data
												} else {
													that.oneLoginBtn.load = false;
													U.qerror('单位为空，请联系管理');
												}

											} else {
												U.qerror(res.msg);
											}

										});



									}
								});
							}
						},
						complete: function() {
							that.oneLoginBtn.load = false;
						}
					});
				}
			},
			login() {


			},
			// APP一键登录
			appOneLogin() {
				const that = this,
					U = that.U;

				// 登录
				that.oneLoginBtn.load = true, U.qloading('登录中...');
				console.log('开始app微信登录');
				uni.login({
					provider: 'weixin',
					scopes: 'auth_base',
					success: function(lres) {
						console.log('登录成功', lres);

						//#ifdef MP-WEIXIN
						if (!uni.getUserProfile) {
							U.qerror('微信小程序基础版本小于2.10.4');
						} else {
							U.qinfo('获取绑定手机号登录');

							// uni.getUserProfile({
							// 	desc: '展示给用户',
							// 	lang: 'zh_CN',
							// 	success: function (lires) {
							// 		console.log('登录信息aaaa', lires);

							// 		// // 微信昵称
							// 		// lo.nickName = lires.userInfo.nickName;
							// 		// // 头像图片
							// 		// lo.avatarUrl = lires.userInfo.avatarUrl;

							// 		// // 保存微信登录信息
							// 		// uni.setStorageSync(that.C.WX_LINFO, lo);

							// 		// console.log('用户信息', uni.getStorageSync(that.C.WX_LINFO));
							// 	},
							// 	fail: function(err){
							// 		console.log('调用失败', err);
							// 	}
							// });

							// uni.getUserProfile({
							// 	desc: '获取你的昵称、头像、地区及性别',
							// 	success: res => {
							// 		console.log(res);
							// 		console.log(1);
							// 	},
							// 	fail: res => {
							// 		console.log(2);
							// 		console.log(res)
							// 		//拒绝授权
							// 		uni.showToast({
							// 			title: '您拒绝了请求,不能正常使用小程序',
							// 			icon: 'error',
							// 			duration: 2000
							// 		});
							// 		return;
							// 	}
							// });

						}
						//#endif

						//#ifdef APP-PLUS
						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(lires) {
								console.log('登录信息', lires);

								let lo = {};
								// 授权code
								lo.code = lres.authResult.code;
								// 微信openid
								lo.openid = lres.authResult.openid;
								// 微信unionid（微信和小程序通用id）
								lo.unionid = lres.authResult.unionid;
								// 微信昵称
								lo.nickName = lires.userInfo.nickName;
								// 头像图片
								lo.avatarUrl = lires.userInfo.avatarUrl;

								let ps = {
									// 登录设备
									device: 'APP',
									// 车队编号
									teamNo: '8112010001',
									// 用户openid
									wxid: lo.openid,
									// 登录角色
									lrole: 'TEAM_DRIVER',
									// 登录手机号
									lphone: '18108208118',
									// 登录密码
									lpass: '123456'
								};
								that.$u.api.passLogin(ps).then((res) => {
									if (res.code != 1) {
										U.qalert(res.msg);
									} else {
										// 保存微信登录信息
										uni.setStorageSync(that.C.WX_LINFO, lo);
										uni.setStorageSync('staffState', loginres.data.luser.staffState);
										console.log('用户信息', uni.getStorageSync(that.C
											.WX_LINFO));

										// 保存登录用户信息
										uni.setStorageSync(that.C.uuid, res.uuid);

										// 跳转到tabbar主页
										uni.switchTab({
											url: '/pages/tabbar/order-list/order-list'
										});
									}
								});
							}
						});
						//#endif
					},
					fail: function(error) {
						console.log('登录失败', error);
						U.qerror('登录失败');
					},
					complete: function() {
						console.log('最后进来吗？');
						that.oneLoginBtn.load = false, U.qclose();
					}
				});
			},
			// 导航-手机/账号登录页面
			goLogin() {
				uni.setStorageSync('loginId', '1');
				uni.navigateTo({
					url: '/pages/common/login/login'
				})
			}
		}
	}
</script>

<style lang="less">
	.auth-index {
		.logo {
			margin-top: 150rpx;
			margin-left: calc((100% - 160rpx)/2);

			.logo-img {}
		}

		.fotter {
			padding: 10rpx 5rpx;
			position: fixed;
			bottom: var(--window-bottom);

			.btns {
				margin-bottom: 20rpx;
				display: flex;
				justify-content: space-around;
			}

			.login-tip {
				margin-bottom: 20rpx;
				color: #666666;
				font-size: 24rpx;
			}
		}
	}
</style>